package com.ordering.action.util;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.ordering.util.DateAndTime;
import com.ordering.util.ImageThread;

import com.ordering.action.BaseAction;
import com.ordering.constant.Constants;

public class FileUploadAction  extends BaseAction
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/** 业务类型：0：文本编辑器 */
    private static final int TYPE_FCK_EDITER = 0;
    /** 业务类型：1：商品 */
    private static final int TYPE_GOODS = 1;
    /** 业务类型：2：众筹 */
    private static final int TYPE_CROWDFUNDING = 2;
    /** 业务类型：3：会员 */
    private static final int TYPE_MEMBER = 3;
    /** 业务类型：4：拍卖活动 */
    private static final int TYPE_GOODSAUCTIONS = 4;
    /** 业务类型：5：商品分类 */
    private static final int TYPE_GOODSCATEGORY = 5;
    /** 业务类型：6：艺术家类 */
    private static final int TYPE_ARTIST = 6;
    /** 业务类型：7：资讯 */
    private static final int TYPE_INFORMATION=7;
    /** 业务类型：8：众筹回报 */
    private static final int TYPE_CROWDFUNDING_REPAY = 8;
    /** 业务类型：9：基金投资 */
    private static final int TYPE_INVEST = 9;
    /** 业务类型：10：保险投资 */
    private static final int TYPE_INSURANCE = 10;
    
    private static final String IMAGE_PATH = "/imageFile/";
    private static final String TYPE_CROWDFUNDING_PATH = "crowdfundingFile";
    private static final String TYPE_MEMBER_PATH = "memberFile";
    private static final String TYPE_GOODSAUCTIONS_PATH = "goodsAuctionsFile";
    private static final String TYPE_GOODSCATEGORY_PATH = "goodsCategoryFile";
    private static final String TYPE_ARTIST_PATH = "artistFile";
    private static final String TYPE_FCK_EDITER_PATH = "ipiediter";
    private static final String TYPE_INFORMATION_PATH = "informationFile";
    private static final String TYPE_CROWDFUNDING_REPAY_PATH = "crowdfundingRepayFile";
    private static final String TYPE_INVEST_FUND_PATH = "fundFile";
    private static final String TYPE_INVEST_INSURANCE_PATH = "insuranceFile";
    
    private static final String PATH_PICTURE = "pictures";
    private static final String PATH_VIDEO ="video";
    private static final String PATH_SMALL_SMALL = "smallsmall";
    private static final String PATH_SMALL = "small";
    private static final String PATH_BIG = "big";
    private static final String PATH_BIG_BIG = "bigbig";
    private static final String PATH_MIDDLE = "middle";
    private static final String PATH_MIDDLEBIG = "middlebig";
    private static final String PATH_ORIGINAL = "original";
    
    
    
    public void add() throws Exception
    {
    	
    	request.setCharacterEncoding("utf-8"); // 设置编码
        JSONObject resultJson = new JSONObject();
        try
        {
            // 业务类型，用于判断保持的目录
            String reqParam = request.getParameter("reqParam");
            System.out.println(reqParam);
            //JSONObject reqJson = JSONObject.fromObject(reqParam);

            // 编号，用于保存附件时命名
            //String businessNo = reqJson.getString("businessNo");
            // 存放附件文件
            List<FileItem> fileItemList = new ArrayList<FileItem>();
            // 获得磁盘文件条目工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setRepository(new File(request.getSession().getServletContext().getRealPath("/")));
            // 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
            factory.setSizeThreshold(1024 * 1024);
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 获取所有表单里的域
            List<FileItem> allItemList = (List<FileItem>) upload.parseRequest(request);
            for (FileItem item : allItemList)
            {
                // 分文本域和文件域
                if (!item.isFormField())
                {
                    // 如果是附件，将附件
                    fileItemList.add(item);
                }
            }
            
//            if (StringUtils.isBlank(businessNo))
//            {
//                resultJson.put("result", 1);
//                resultJson.put("msg", "没有文件编号！");
//                outPutMessage( resultJson.toString());
//                return;
//            }

            if (fileItemList.isEmpty())
            {
                resultJson.put("result", 1);
                resultJson.put("msg", "没有文件！");
                outPutMessage( resultJson.toString());
                return;
            }

            
            List<String> fileNames = new ArrayList<String>();
            for(FileItem fm : fileItemList)
            {
                String oldFileName = fm.getName();
                fileNames.add(saveFile(fm.get(),UUID.randomUUID().toString() + ".jpg"));
            }
//            List<String> fileNames = upload(fileItemList, Integer.valueOf(businessType), businessNo);

            resultJson.put("result", 0);
            resultJson.put("data", fileNames);
        }
        catch (Exception e)
        {
            resultJson.put("result", 1);
            resultJson.put("msg", "上传文件发生错误，请联系管理员！");
        }
        outPutMessage(resultJson.toString());
    	
    	
    }
    
    
    private String saveFile(byte[] fileByte,String saveFileName) throws Exception{
//    	String saveFilePath = DateAndTime.getDate();
//
//        saveFilePath = IMAGE_PATH.concat("/").concat(saveFileName.substring(0, saveFileName.lastIndexOf("/")));
        
    	
    	
    	
    	
    	String path =  saveFileExc(fileByte, saveFileName, IMAGE_PATH,new String[]{IMAGE_PATH}, new int[]{200}, new int[]{200});

        return path;
    }
    
    /**
     * 保存图片文件，并生成不同规格的图片文件（注意，该方法生成不同规格图片文件只支持图片文件）
     * @param item 文件项
     * @param saveFileName 保存的文件名，不包含后缀名
     * @param saveFilePath 文件保存路径
     * @param newFilePaths 生成新文件保存路径，为null或者Length=0时，只保存原文件
     * @param toWidths 生成新文件宽度规格，Length与newFilePaths一致
     * @param toHeights 生成新文件高度规格，Length与newFilePaths一致
     * @return
     * @throws Exception
     */
    private String saveFileExc(byte[] fileByte, String saveFileName, String saveFilePath, String[] newFilePaths, int[] toWidths, int[] toHeights) throws Exception
    {
        // 保存文件的目录
        // 附件保存地址（配置）
//        
//        SmbFile saveFile = new SmbFile(saveFilePath);
//        synchronized (saveFile)
//        {
//            if (!saveFile.exists() && !saveFile.isDirectory())
//            {
//                saveFile.mkdirs();
//            }http://192.168.0.152:8080/artTradeFile/goodsAuctionsFile/20150312/picturesoriginal/E20150312164240040001.jpg.jpg
//        }
        String smbFilePath = Constants.FILE_PATH.concat("/").concat(saveFilePath);
        // 获取路径名
//        String oldFileName = item.getName();
        if(saveFileName.contains("/"))
        {
            smbFilePath = smbFilePath.concat(saveFileName.substring(0, saveFileName.indexOf("/")));
        }
        // 源文件
//        SmbFile saveFile = new SmbFile(smbFilePath.concat("/").concat(PATH_ORIGINAL));
//        synchronized (saveFile)
//        {
//            if (!saveFile.exists() && !saveFile.isDirectory())
//            {
//                saveFile.mkdirs();
//            }
//        }
        SmbFile smsFile = new SmbFile(saveFilePath, saveFileName);
        // 保存原图
//        item.write(file);
//        SmbFileOutputStream smbOut = null;
//        try
//        {
//            smbOut = new SmbFileOutputStream(smsFile);
//            smbOut.write(fileByte);
//        }
//        catch (Exception e)
//        {
//            throw e;
//        }
//        finally
//        {
//            if(smbOut != null)
//                smbOut.close();
//        }
        
        if(newFilePaths != null && newFilePaths.length > 0)
        {
            new ImageThread(smsFile, newFilePaths, toWidths, toHeights).run();
        }
        return saveFilePath.concat(saveFileName);
    }
    
    private void outPutMessage(String jsonStr) throws IOException{
	    String contentType = "text/html;charset=utf-8";
		//指定输出内容类型和编码  
        ServletActionContext.getResponse().setContentType(contentType);   
        //获取输出流，然后使用  
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        out.print(jsonStr);
        out.flush();  
        out.close(); 
	}
}
